package com.hb.trade.api.push.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.project.portal.dto.PortalNoticeDTO;
import com.hb.core.pojo.project.portal.entity.PortalNotice;
import com.hb.core.util.CronExpressionUtil;
import com.hb.trade.api.push.util.HttpUtil;
import com.hb.trade.client.project.PortalNoticeClient;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.model.msg.Message;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 将公告推送至共用门户
 *
 * @author tian
 * @date 2022年05月26日 14:54
 */
@Slf4j
@Component
public class PushNoticeTask {

    // 保存门户公告的方法
    private final static String METHOD_NAME = "/portal/v1.0/portalNotice/savePortalNotice";

    protected final PortalNoticeClient portalNoticeClient;

    public PushNoticeTask(PortalNoticeClient portalNoticeClient){
        this.portalNoticeClient = portalNoticeClient;
    }



    /**
     * 将公告推送至共用门户
     *
     * @author tian
     * @date 2022-5-26 15:54
     */
    @Scheduled(cron = CronExpressionUtil.WHOLE_TEN)
    public void tenderProjectPhase(){
        // 是否需要同步公共平台（赢标saas版）
        Boolean status = Boolean.valueOf(SpringUtil.getProperty("push.status"));
        // 同步公共平台的url
        String url = SpringUtil.getProperty("push.url");
        // 平台标识
        String receiveType = SpringUtil.getProperty("push.receiveType");

        if(status){
            // 查询未同步的门户公告
            PortalNoticeDTO portalNoticeDTO = new PortalNoticeDTO();
            portalNoticeDTO.setPushStatus(0);
            Message<List<PortalNoticeDTO>> listMessage = portalNoticeClient.listPortalNoticeByPushStatus(portalNoticeDTO);
            if(listMessage.isSuccess() && CollUtil.isNotEmpty(listMessage.getData())){
                for (PortalNoticeDTO portalNotice:listMessage.getData()) {
                    portalNotice.setReceiveType(receiveType);
                    String param = JSONUtil.toJsonStr(portalNotice);
                    HttpUtil.sendPost(url + METHOD_NAME, param);
                }
                //推送完成后将数据标记为已推送
                List<Long> ids = listMessage.getData().stream().map(PortalNotice::getId).collect(Collectors.toList());
                portalNoticeClient.updatePushStatusByIds(ids);
            }
        }
    }
}
